package demo.db.mybatis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import demo.db.mybatis.dao.UserMapper;
import demo.db.mybatis.pojo.User;
import demo.java.lang.annotation.DataSource;

@Service
public class UserService {

    @Autowired
    private UserMapper mapper;

    @DataSource(DataSource.slave)
    public User query(int id) {
        return mapper.selectById(id);
    }

    @DataSource(DataSource.master)
    public User insert(String name) {
        User user = new User();
        user.setName(name);
        user.setStatus((byte) 5);
        mapper.addNewUser(user);
        return user;
    }

    @DataSource(DataSource.master)
    public void insertAndFlagIfCommit(String name) {
        User user = insert(name);
        System.err.println(user);
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                System.err.println("send email after transaction commit...");
            }
        });
        System.err.println("this method complete....");
    }

    public int add(String name) {
        return mapper.insertUser(name, (byte) 9);
    }

}
